<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<view class="content detail">
			<!--客户信息-->
			<view class="detail-item">
				<uni-section title="客户信息" type="line"></uni-section>
				<view class="detail-content formRef">
					<uni-forms ref="formRef" :model="formData" :rules="formRules" labelWidth="80px">
					  <uni-forms-item label="区域" name="regionCode">
					    <uni-data-select
					    	v-model="formData.regionCode"
					    	placeholder="请选择区域"
					    	:localdata="setStore.allProvinceList"></uni-data-select>
					  </uni-forms-item>
						<uni-forms-item label="客户姓名" name="name">
					    <uni-easyinput v-model="formData.name" placeholder="请输入客户姓名" />
					  </uni-forms-item>
						<view v-if="checkPermi(['zhouyz:customer:money'])">
							<uni-forms-item label="客户余额" name="balance">
							  <uni-easyinput type="number" v-model="formData.balance" placeholder="请输入客户余额" />
							</uni-forms-item>
							<uni-forms-item label="客户积分" name="integral">
							  <uni-easyinput type="number" v-model="formData.integral" placeholder="请输入客户积分" />
							</uni-forms-item>
							<uni-forms-item label="会员等级" name="levelId" v-if="checkPermi(['zhouyz:customerLevel:list'])">
							  <uni-data-select
							  	v-model="formData.levelId"
							  	placeholder="请选择会员等级"
							  	:localdata="customerLevelList"></uni-data-select>
							</uni-forms-item>
						</view>
					  <uni-forms-item label="公司名称" name="company">
					    <uni-easyinput v-model="formData.company" placeholder="请输入公司名称" />
					  </uni-forms-item>
						<uni-forms-item label="信用代码" name="companyCode">
						  <uni-easyinput v-model="formData.companyCode" placeholder="请输入信用代码" />
						</uni-forms-item>
						<uni-forms-item label="区域详情" name="province">
							<ty-data-picker
								placeholder="请选择区域"
								v-model="formData.province"
								@change="onChange">
							</ty-data-picker>
						</uni-forms-item>
						<uni-forms-item label="营业执照" name="businessLicenseImg">
							<up-upload
								:fileList="fileList.businessLicenseImg"
								@afterRead="afterRead"
								@delete="deletePic"
								name="businessLicenseImg"
								:maxCount="1"
								></up-upload>
						  <uni-easyinput style="display: none;" v-model="formData.businessLicenseImg" placeholder="上传营业执照" />
						</uni-forms-item>
					  <uni-forms-item label="门店照片" name="storeImg">
							<up-upload
								:fileList="fileList.storeImg"
								@afterRead="afterRead"
								@delete="deletePic"
								name="storeImg"
								:maxCount="1"
								></up-upload>
					    <uni-easyinput style="display: none;" v-model="formData.storeImg" placeholder="上传门店照片" />
					  </uni-forms-item>
					  <uni-forms-item label="形象照片" name="storeFaceImg">
							<up-upload
								:fileList="fileList.storeFaceImg"
								@afterRead="afterRead"
								@delete="deletePic"
								name="storeFaceImg"
								:maxCount="1"
								></up-upload>
					    <uni-easyinput style="display: none;" v-model="formData.storeFaceImg" placeholder="上传形象照片" />
					  </uni-forms-item>
					</uni-forms>
					<button type="primary" :disabled="isSubmit" :loading="isSubmit" @click="submit">提交</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set'
import { timeFormat } from 'uview-plus'
import { customerAdd, customerInfo, customerLevel } from "@/api/erp_api/customer"
import { allProvince } from "@/api/erp_api/region"
import { upload } from "@/api/system/common"
import { getUserLocation, arrText } from '@/utils/ty.js';
import { wholesalerList, examineFlagList, extendFlagList } from '@/utils/config.js';

	const userStore = useUserStore()
	const setStore = useSetStore()
	const id = ref('')
	onLoad(async (option) => {
		if (checkPermi(['zhouyz:customerLevel:list'])) {
			await getCustomerLevel()
		}
		if (option.id) {
			uni.setNavigationBarTitle({
				title: '修改客户'
			})
			id.value = option.id
			getDetail()
		}
	})
	
	// 获取会员等级
	const customerLevelList = ref([])
	const getCustomerLevel = () => {
		return customerLevel({
			pageNum: 1,
			pageSize: 30
		}).then(res => {
			customerLevelList.value = res.rows.map(item => {
				return {
					...item,
					levelValue: item.value,
					value: item.id,
					text: item.name
				}
			}) || []
		})
	}
	
	// 选择省市区
	const onChange = (e) => {
	}
	
	// 获取详情
	const info = ref({})
	const isLoading = ref(false)
	const getDetail = () => {
		const params = {
			id: id.value
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		customerInfo(params).then(res => {
			info.value = res.data || {}
			formData.value = {
				province: res.data.province,
				regionCode: res.data.regionCode,
				name: res.data.name,
				balance: res.data.balance,
				integral: res.data.integral,
				levelId: res.data.levelId,
				company: res.data.company,
				companyCode: res.data.companyCode,
				spreadCode: res.data.spreadCode,
				businessLicenseImg: res.data.businessLicenseImg,
				storeImg: res.data.storeImg,
				storeFaceImg: res.data.storeFaceImg
			}
			fileList.value = {
				businessLicenseImg: imgUrlList(res.data, 'businessLicenseImg'),
				storeImg: imgUrlList(res.data, 'storeImg'),
				storeFaceImg: imgUrlList(res.data, 'storeFaceImg')
			}
			isLoading.value = false
			uni.hideLoading()
	  }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	// 图片显示
	const imgUrlList = (data, key) => {
		return data[key] ? data[key].split(',').map(item => {
			return {
				status: 'success',
				message: '上传成功',
				url: item,
				type: 'image'
			}
		}) : []
	}
	
	// 图片上传
	const fileList = ref({
		businessLicenseImg: [],
		storeImg: [],
		storeFaceImg: []
	})
	
	// 删除图片
	const deletePic = (event) => {
	  fileList.value[`${event.name}`].splice(event.index, 1)
		formData.value[`${event.name}`] = fileList.value[`${event.name}`].map(item => item.url).join(',')
	}
	
	// 新增图片
	const afterRead = async (event) => {
	  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	  let lists = [].concat(event.file)
	  let fileListLen = fileList.value[`${event.name}`].length
	  lists.map((item) => {
	    fileList.value[`${event.name}`].push({
	      ...item,
	      status: 'uploading',
	      message: '上传中',
	    });
	  });
	  for (let i = 0; i < lists.length; i++) {
	    const result = await upload(lists[i].url)
			const data = JSON.parse(result.data)
	    let item = fileList.value[`${event.name}`][fileListLen]
	    fileList.value[`${event.name}`].splice(fileListLen, 1, {
	      ...item,
	      status: 'success',
	      message: '',
	      url: data.url,
	    });
	    fileListLen++;
	  }
		formData.value[`${event.name}`] = fileList.value[`${event.name}`].map(item => item.url).join(',')
	};
	
	// form表单数据
	const formData = ref({
		province: '',
		regionCode: '',
		name: '',
		balance: '',
		integral: '',
		levelId: '',
		company: '',
		companyCode: '',
		spreadCode: '',
		businessLicenseImg: '',
		storeImg: '',
		storeFaceImg: ''
	})
	const formRef = ref(null)
	const formRules = ref({
		name: {
			rules: [{ required: true, errorMessage: '请输入客户姓名' }]
		}
	})
	const isSubmit = ref(false)
	// 提交
	const submit = () => {
		formRef.value.validate().then(formRes => {
			const params = { ...info.value,...formRes }
			if (id.value) {
				params.id = id.value
			}
			if (params.levelId) {
				const levelFilter = customerLevelList.value.filter(item => item.id == params.levelId)
				params.levelName = levelFilter[0]?.name
				params.levelValue = levelFilter[0]?.levelValue
			}
			isSubmit.value = true
			customerAdd(params).then(async (res) => {
				modal.showToast(res.msg)
				await uni.$u.sleep(1000)
				isSubmit.value = false
				clear()
				uni.$emit('refreshList');  // 触发刷新事件
				uni.navigateBack({
					delta: 1
				})
			}).catch((err) => {
				modal.showToast(err)
				isSubmit.value = false
			})
		})
	}
	// 清空
	const clear = () => {
		formData.value = {
			province: '',
			regionCode: '',
			name: '',
			balance: '',
			integral: '',
			levelId: '',
			company: '',
			companyCode: '',
			spreadCode: '',
			businessLicenseImg: '',
			storeImg: '',
			storeFaceImg: ''
		}
	}
</script>

<style scoped lang="scss">
	.vertical {
		flex-direction: column !important;
		.price {
			&-tip {
				background-color: #ff66cc;
			}
			&-item {
				padding: 5px 0;
				&-bottom {
					margin-top: 10px;
				}
				&-td {
					padding: 0 5px;
					font-size: 12px !important;
					:deep(.uni-easyinput__content-input) {
						height: 26px;
						font-size: 12px;
					}
					&-tag {
						background-color: #d1e9ff;
						border-color: #d1e9ff;
						color: #1890ff;
					}
				}
				&+.price-item {
					margin-top: 10px;
				}
			}
		}
	}
</style>
